from utlis.smscode import sms_code
import re
from qiniu import Auth, put_file, etag
import qiniu.config
from utlis.CORS import BaseHandler
from myredis import r
from captcha.captcha import captcha
from utlis.my_jwt import jj
from utlis.mysql import db
#开启debug模式
settings = {'debug' : True}
# 配置跨域
#生成短信验证码
# class Imgcode(BaseHandler):
#     def get(self):
#         name,text,img=captcha.generate_captcha()
#         uuid=self.get_query_argument("uuid")
#         r.set_str(uuid,text,60)
#         res=r.get_str(uuid)
#         print(res.decode())
#         self.set_header('Content-Type','image/jpg')
#         self.write(img)
# 容联云发送验证码
class Smscode(BaseHandler):
    def get(self):
        mobile=self.get_query_argument("mobile")
        uuid=self.get_query_argument("uuid")
        imgcode=self.get_query_argument("imgcode")
        ip=self.request.remote_ip
        print("url>>>>>",ip)
        if not all([mobile,uuid,imgcode]):
            self.finish({"code":400,'msg':'字段不完整'})
            return
        ipi=r.get_str(ip)
        if ipi:
            self.finish({"code":400,'msg':"请等一分钟后再次发送"})
            return
        # res=r.get_str(uuid)
        # if not  res:
        #     self.finish({"code":400,'msg':'验证码已过期，请点击刷新'})
        #     return
        # if res.decode().lower()!=imgcode.lower():
        #     self.finish({"code":400,'msg':'验证码错误'})
        #     return
        if not re.findall(r"^1[3-9]\d{9}$",mobile):
            self.finish({"code":400,'msg':'手机号格式错误'})
            return
        res=r.get_str(mobile)
        # if res!=None:
        #     self.finish({"code":400,'msg':'一分钟只能发送一次'})
        #     return
        res=sms_code(mobile)
        r.set_str(ip,"用户ip",20)
        self.finish({"code":200,'msg':"发送成功，请注意查收"})
# 移动端网络登录端口
import json
class moveLogin(BaseHandler):
    def post(self):
        data=self.request.body
        mes=json.loads(data)
        mobile=mes["mobile"]
        smscode=mes["smscode"]
        print("mobile>>>>>",mobile)
        print("smscode>>>>",smscode)
        if not all([mobile,smscode]):
            self.finish({"code":400,'msg':'字段不完整'})
        smscode1=r.get_str(mobile)
        if not smscode1:
            self.finish({"code":400,'msg':'验证码过期，请重新发送'})
        print(">>>>>>>>>>>>>>>",smscode1.decode())
        if smscode1.decode()!=smscode:
            self.finish({"code":400,'msg':'验证码错误'})
        sql=f"""select * from user where mobile={mobile}"""
        res=db.findone(sql)
        if res:
            datas={"data":{
                'id':res['id'],
                'mobole':res['mobile'],
                'url':res['url'],
                'score':res['score'],
                'level':res['level']
            }}
            token=jj.jwt_encode(datas)
            self.finish({"code":200,'msg':'登陆成功','token':token,'uid':res['id']})
            return
        else:
            self.finish({"code":400,'msg':'登录失败，没有该用户'})
            return


# 拉起微博第三方接口
class Surl(BaseHandler):
    def get(self):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        self.finish({"code":200,'msg':url})
# 从第三方获取token


import requests,time
class Ssctoken(BaseHandler):
    def get(self):
        # 获取code
        code = self.get_query_argument("code")
        # 向access_token接口发送post请求
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        # 根据返回结果操作
        # 获取token和uid
        message = json.loads(res.text)
        token = message['access_token']
        uid = message['uid']
        # 查询数据库中是否存在，如果存在用用户信息生成jwt token返回
        sql = "select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.udi='%s'" % (
            str(uid))
        user = db.findone(sql)
        if user:
            # 生成jwt
            # 返回jwt token
            token = jj.jwt_encode(
                data={"data": {"uid": user['id'], "mobile": user['mobile'], 'exp': int(time.time())}})
            self.redirect("http://localhost:8080/sf_zhong?token="+token+"&userid="+str(user['id']))

        else:
            # 绑定
            self.redirect("http://localhost:8080/login1?token="+str(token)+"&uid="+str(uid))
# api.add_resource(Ssctoken,"/user/weiboCallback/")


# 绑定用户
class Sbd(BaseHandler):
    def post(self):
        # 接收参数
        data = self.request.body
        data=json.loads(data)
        print(data['uid'])
        print(data['mobile'])
        print(data['token'])
        sq=f"""select * from user where mobile = {data['mobile']}"""
        res=db.findone(sq)
        if res:
            s=f"""insert into sf_login(userid,webfrom,udi,token) values({res["id"]},'weibo','{data['uid']}','{data['token']}')"""
            db.update(s)
            token = jj.jwt_encode(data={"data": {
                "uid": res['id'], "mobile": data['mobile']}})
            self.finish({"code": 200, "token": token, "userid": res['id']})
            return
        # 加入用户表
        sql = "insert into user(mobile) values('%s')" % (data['mobile'])
        userid = db.update(sql)
        print(userid)
        # 加入三方登录表
        sql2 = "insert into sf_login(userid,webfrom,udi,token) values(%d,'weibo','%s','%s')" % (userid, data['uid'], data['token'])
        db.add(sql2)
        db.commit()
        # 返回jwt token
        token = jj.jwt_encode(data={"data": {
                                 "uid": userid, "mobile": data['mobile']}})
        self.finish({"code": 200, "token": token, "userid": userid})
        return
#七牛云上传图片
class imgqny(BaseHandler):
    def get(self):
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'VWKXpfhRZSeT-SMMo4HEJ708LO6pd4rBBToTQv36'
        secret_key = 'CpX7R__itUIcFNH-JQ2uop1Wu-syEoAQvlkhp0SR'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'adminctg'
        # 上传后保存的文件名
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name)
        self.finish({"code":200,'token':token})

from baidu import bd
# 根据图片获取信息
class character(BaseHandler):
    def post(self):
        "http://rpuhgscze.hb-bkt.clouddn.com/1.jpg"
        data = self.request.body
        data = json.loads(data)
        print("dataurl",data["imgurl"])
        # 调取接口进行传参
        res = bd.getmes(data['imgurl'])
        # 给获取到的数据内容赋值
        res0=res[0]['words']
        res1 = res[1]['words']
        # 切片取出前17位
        res3=res0[0:17]
        print(type(res0))
        print(type(res1))
        try:
            # 判断里面是否是数字
            int(res3)
            # 如果是数字就进行赋值，第一个是身份证号码，第二个是用户姓名
            res0 = res[1]['words']
            res1 = res[0]['words']
            self.finish({"code": 200, 'msg': res0, 'msg2': res1})
            # 如果不是数字就把赋值内容颠倒，第2个是身份证号码，第1个则是用户姓名
        except:
            res1 = res[1]['words']
            res0 = res[0]['words']
            self.finish({"code":200,'msg':res0,'msg2':res1})

import uuid,os

class Locality(BaseHandler):
    def post(self):
        # 获取到前端传递过来的流（file）
        file = self.request.files.get("file",None)
        for i in file:
            # filename:流中的图片名
            filename = i["filename"]
            # filename:微信图片_20230213114351.png
            # 用点分割把png分隔下来
            # 对图片重命名
            arr = filename.split(".")
            #  .hex意在去除uuid中的横杠(-)
            name = uuid.uuid1().hex
            # 唯一值 + . + 后缀png
            newname = name + "." + arr[1]
            # 在urls里面配置的存储路径
            path = os.path.join(self.settings["MEDIA_ROOT"],newname)
            with open(path,'wb') as a:
                a.write(i["body"])
            r.list_rpush('baiduapi',path)
            content = bd.contentmes(path)
            print("content>>>>>>",content)
            aa=json.loads(content)
            # print(aa)
            self.finish({"code": 200, "msg": "获取成功", "name": aa["words_result"][0]['words'],
                                "ID_user": aa["words_result"][1]['words']})
def getBaidu():
    while True:
      list=r.list_getall("baiduapi",0,1)
      for i in list:
        content=bd.contentmes(i)
        r.set_str(i,json.dumps(content))
        r.list_lpop("baiduapi")
        time.sleep(1)

import requests

def gettoken():
    key = 'banktoken'
    rekey = 'rebanktoken'
    token = r.get_str(key)
    retoken = r.get_str(rekey)
    if not token:
        res = requests.post("http://localhost:5000/login/",{'name':'小明','pwd':'ctg123456'})
        print(res,"发送请求中")
        user = json.loads(res.text)
        print('user**********************',user)
        token = user['token']
        retoken = user['retoken']
        r.set_str(key,token)
        r.set_str(rekey,retoken)
        # 登陆成功返回 token
        return token
    mes = requests.get(f"http://localhost:5000/checktoken/?token={token}")
    print(mes)
    mm = json.loads(mes.text)
    print('mm',mm)
    code = mm['code']
    if code == 400:
        # 通过刷新 retoken 接口个token刷新延长时间
        rrtoken = requests.post("http://localhost:5000/login/",data={'retoken':retoken})
        rtokenmes =json.loads(rrtoken.text)
        if rtokenmes['code'] == 200:
            token = rtokenmes['token']
            r.set_str(key,rtokenmes['token'])
            r.set_str(rekey,rtokenmes['retoken'])
        else:
            # 刷新token失败mretoken也失效，重新登陆
            res = requests.post("http://localhost:5000/login/",{'name':'zs','pwd':'123'})
            user = json.loads(res.text)
            print(user)
            token = user['token']
            retoken = user['retoken']
            r.set_str(key,token)
            r.set_str(rekey,retoken)
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>存了存了存了")
        return token


from db2 import db1
class OpenbankHandler(BaseHandler):
    def get(self):
            status = 1
            id = self.get_query_argument('id')
            print(status)
            sql = "update open_bank set status='%s' where id=%d" % (status, int(id))
            db.add(sql)
            db.commit()
            print("修改了修改了>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            self.redirect("http://localhost:8080/")

    def post(self):
        print("***")
        data = self.request.body
        mes = json.loads(data)
        username = mes['name']
        identity = mes['certificate']
        bank_code = mes['bank_code']
        mobile = mes['mobile']
        uid=mes['userid']
        password=mes['password']
        url=mes['url']
        if not all([url,id,identity,bank_code,mobile]):
            self.finish({"code":400,'msg':'参数不完整'})
        sql1 = "select * from open_bank where bank_code='%s'" % bank_code
        print(sql1)
        res = db.findone(sql1)
        if res:
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            sql = "insert into open_bank(userid, image_url, code, username, bank_code, mobile, pay_password, status) values (%d,'%s','%s','%s','%s','%s','%s',1)" % (
            int(uid), url, username, identity, bank_code, mobile, password, 0)
            ress = db.update(sql)
            aaa=requests.get(f"http://127.0.0.1:8000/Diaoqudisanf/?id={ress}")
            print('res>>>>>>>>>>>>>>>>>>>>>>>',aaa)
            print("ress>>>>>>>>>>>>>>>",ress)
            db.commit()
            print('*******', ress)
            token = gettoken()
            print("111111111111111111111111111111111111111111111111111111111111111")
            urll=f"http://localhost:5000/open_bank/?username={username}&code={identity}&bank_code={bank_code}&mobile={mobile}&id={ress}&token={token}&url={url}"
            print(urll)
            self.redirect(urll)
























